/*
 * Created on Mar 19, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.ui.command;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;

import edu.mit.simile.longwell.Profile;
import edu.mit.simile.longwell.query.IQueryModel;
import edu.mit.simile.longwell.ui.FlairMessage;

/**
 * @author dfhuynh
 */
public class ExportCommand implements IFlairCommand {

	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.ui.command.IFlairCommand#execute(edu.mit.simile.longwell.ui.FlairMessage)
	 */
	public void execute(FlairMessage msg) throws ServletException {
		String format = msg.m_query.getFirstParamValue("format");
		if (format == null) {
			format = "N3";
		}
		setContentType(format, msg.m_response);
		
		String pseudoURI = msg.m_query.getFirstParamValue("pseudoURI");
		if (pseudoURI != null) {
			exportOne(msg, pseudoURI, format);
		} else {
			exportMany(msg, format);
		}
	}

	protected void exportOne(FlairMessage msg, String pseudoURI, String format) throws ServletException {
		Profile profile = msg.getProfile();
		Model model = ModelFactory.createDefaultModel();
		
		profile.extractObject(
				profile.getSchemaModel().pseudoURIToResource(pseudoURI),
				model);
		
		try {
			model.write(msg.m_response.getOutputStream(), format);
		} catch (IOException e) {
			throw new ServletException(e);
		} finally {
			model.close();
		}
	}
	
	protected void exportMany(FlairMessage msg, String format) throws ServletException {
		Profile profile = msg.getProfile();
		Model model = ModelFactory.createDefaultModel();
		
		try {
			IQueryModel queryModel = (IQueryModel)
			profile.getStructuredModel(IQueryModel.class);
		
			Set objects = queryModel.queryObjects(msg.m_query, false);
			Iterator i = objects.iterator();
			while (i.hasNext()) {
				Resource r = (Resource) i.next();
	
				profile.extractObject(r, model);
			}
			
			model.write(msg.m_response.getOutputStream(), format);
		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			model.close();
		}
	}
	
	protected void setContentType(String format, HttpServletResponse response) {
		if ("RDF/XML".equals(format)) {
			response.setContentType("application/rdf+xml");
		} else if ("N3".equals(format)) {
			response.setContentType("application/n3");
		} else {
			response.setContentType("text/plain");
		}
	}
}
